package com.shinbada.modules.sys.web;

import com.shinbada.common.json.AjaxJson;
import com.shinbada.common.tree.TreeUtil;
import com.shinbada.common.utils.StringUtils;
import com.shinbada.config.properties.ShinProperites;
import com.shinbada.core.web.BaseController;
import com.shinbada.modules.sys.company.CompanyRegister;
import com.shinbada.modules.sys.entity.Office;
import com.shinbada.modules.sys.entity.User;
import com.shinbada.modules.sys.service.OfficeService;
import com.shinbada.modules.sys.utils.DictUtils;
import com.shinbada.modules.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 机构Controller
 *
 * @author initcap
 * @version 2019-5-15
 */
@RestController
@RequestMapping("/sys/office")
@Api(tags = "组织机构管理，域模型维护")
public class OfficeController extends BaseController {

    @Autowired
    private OfficeService officeService;

    @ModelAttribute("office")
    public Office get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return officeService.get(id);
        } else {
            return new Office();
        }
    }

    @RequiresPermissions("user")
    @GetMapping(value = "list")
    @ApiOperation("集合获取")
    public AjaxJson list(Office office) {
        if (office == null || office.getParentIds() == null) {
            return AjaxJson.success().put("list", officeService.findList(false));
        } else {
            return AjaxJson.success().put("list", officeService.findList(office));
        }
    }

    @RequiresPermissions("user")
    @GetMapping("queryById")
    @ApiOperation("根据主键进行查询")
    public AjaxJson queryById(Office office) {
        User user = UserUtils.getUser();
        if (office.getParent() == null || office.getParent().getId() == null) {
            office.setParent(user.getOffice());
        }
        office.setParent(officeService.get(office.getParent().getId()));

        // 自动获取排序号
        if (StringUtils.isBlank(office.getId()) && office.getParent() != null) {
            int size = 0;
            List<Office> list = officeService.findAll();
            for (int i = 0; i < list.size(); i++) {
                Office e = list.get(i);
                if (e.getParent() != null && e.getParent().getId() != null
                        && e.getParent().getId().equals(office.getParent().getId())) {
                    size++;
                }
            }
            office.setCode(office.getParent().getCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size + 1 : 1), 3, "0"));
        }
        return AjaxJson.success().put("office", office);
    }

    @RequiresPermissions("sys:office:register")
    @PostMapping("register")
    @ApiOperation("注册机构数据")
    public AjaxJson register(CompanyRegister register) {
        if (!UserUtils.getUser().isAdmin()) {
            return AjaxJson.error("只有超级管理员可以创建公司，请您联系[天津辛巴达科技发展有限公司]进行创建!");
        }
        String errMsg = beanValidator(register);
        if (StringUtils.isNotBlank(errMsg)) {
            return AjaxJson.error(errMsg);
        }
        officeService.register(register);
        return AjaxJson.success("注册机构成功!");
    }

    @RequiresPermissions(value = {"sys:office:add", "sys:office:edit"}, logical = Logical.OR)
    @PostMapping("save")
    @ApiOperation("保存数据")
    public AjaxJson save(Office office) {
        if (shinProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(office);
        if (StringUtils.isNotBlank(errMsg)) {
            return AjaxJson.error(errMsg);
        }

        officeService.save(office);

        if (office.getChildDeptList() != null) {
            for (String id : office.getChildDeptList()) {
                Office childOffice = new Office();
                childOffice.setName(DictUtils.getDictLabel(id, "sys_office_common", "未知"));
                childOffice.setParent(office);
                childOffice.setType("2");
                childOffice.setUseable(ShinProperites.YES);
                officeService.save(childOffice);
            }
        }
        return AjaxJson.success("保存机构'" + office.getName() + "'成功");
    }

    @RequiresPermissions("sys:office:del")
    @DeleteMapping("delete")
    @ApiOperation("删除数据")
    public AjaxJson delete(Office office) {
        if (shinProperites.isDemoMode()) {
            return AjaxJson.error("演示模式，不允许操作！");
        }
        officeService.delete(office);
        return AjaxJson.success("删除成功！");
    }

    @RequiresPermissions("user")
    @GetMapping("treeData")
    @ApiOperation("获取机构JSON数据，extId:排除的ID，type:类型（1公司；2部门。。。）")
    public AjaxJson treeData(@RequestParam(required = false) String extId, @RequestParam(required = false) String type) {
        List<Office> list = officeService.findList(false);
        List<Office> fileter = filterOfficeByExtIdAndType(list, extId, type);
        return AjaxJson.success().put("treeData", TreeUtil.buildLevelTreeSort(fileter));
    }

    private List<Office> filterOfficeByExtIdAndType(List<Office> list, String extId, String type) {
        if (StringUtils.isNotBlank(extId)) {
            list = list.stream().filter(office -> !office.getParentIds().contains(extId)).collect(Collectors.toList());
        }
        if (StringUtils.isNotBlank(type)) {
            list = list.stream().filter(office -> Integer.parseInt(type) >= Integer.parseInt(office.getType())).collect(Collectors.toList());
        }
        return list;
    }

}
